package cn.com.dpc.service;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;

/**
 * encoder/decoder util
 * @author liangzi
 *
 */
public class CharsetUtil {
	
	private static CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder();
    private static CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder();
    
	public synchronized static ByteBuffer encodeGBK(String msg) {
		CharBuffer charBuffer = CharBuffer.allocate(msg.length());
		charBuffer.put(msg);
		charBuffer.flip();
		ByteBuffer buffer = null;
		try {
			buffer = encoder.encode(charBuffer);
		} catch (CharacterCodingException e) {
			e.printStackTrace();
		}
		return buffer;
	}
	
	public synchronized static String decoderGBK(ByteBuffer buffer) {
		CharBuffer charBuffer = null;
		try {
			charBuffer = decoder.decode(buffer);
		} catch (CharacterCodingException e) {
			e.printStackTrace();
		}
		return charBuffer.toString();
	}

}
